﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Context;
using System.Data;

namespace Scala.Data.Impl.Uow
{
    public class UnitOfWork : IUnitOfWork
    {
        private ISession session;
        private ITransaction transaction;

        public UnitOfWork(ISession session, IsolationLevel level)
        {
            if (session == null) throw new ArgumentNullException("session");

            CurrentSessionContext.Bind(session);
            this.session = session;
            transaction = session.BeginTransaction(level);
        }

        #region IUnitOfWork Members

        public void Commit()
        {
            if (!transaction.IsActive)
            {
                throw new InvalidOperationException("No active transation");
            }
            transaction.Commit();
        }

        public void RollBack()
        {
            if (!transaction.IsActive)
            {
                throw new InvalidOperationException("No active transation");
            }
            transaction.Rollback();
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            if (!transaction.WasCommitted && !transaction.WasRolledBack)
            {
                RollBack();
            }
           
            transaction.Dispose();
            transaction = null;
            CurrentSessionContext.Unbind(session.SessionFactory);
            session.Dispose();                        
        }

        #endregion
    }
}
